﻿using Digitalmes.Domain;
using Digitalmes.Domain.Mes;
using Digitalmes.Scada.Events;
using Digitalmes.Sugar;
using MediatR;

namespace Digitalmes.Scada.MessageHandlers;

internal class Op260AfterArchivedHandler : INotificationHandler<AfterArchivedEvent>
{
    private readonly IServiceProvider _serviceProvider;
    private readonly ILogger _logger;

    public Op260AfterArchivedHandler(IServiceProvider serviceProvider, ILogger<Op260AfterArchivedHandler> logger)
    {
        _serviceProvider = serviceProvider;
        _logger = logger;
    }

    public async Task Handle(AfterArchivedEvent notification, CancellationToken cancellationToken)
    {
        if (notification.State != (int)ErrCode.E0010 || notification.OpCode != "OP260")
        {
            return;
        }

        try
        {
            var customeSN = notification.ReqMessage.GetData("PLC_Archive_CustomSN")?.GetString();
            if (string.IsNullOrEmpty(customeSN))
            {
                return;
            }

            using var scope = _serviceProvider.CreateScope();
            var transSnRepo = scope.ServiceProvider.GetRequiredService<SugarRepository<ProdTransSn>>();
            var transSn = await transSnRepo.GetFirstAsync(s => s.Sn == notification.SN);
            if (!string.IsNullOrEmpty(transSn.CustomerSn))
            {
                return;
            }

            transSn.CustomerSn = customeSN;
            await transSnRepo.UpdateAsync(transSn, s => new
            {
                s.CustomerSn,
            });

            var tranSnRecordRepo = scope.ServiceProvider.GetRequiredService<SugarRepository<ProdTransSnRecord>>();
            var transSnRecord = await tranSnRecordRepo.GetFirstAsync(s => s.Sn == notification.SN);
            transSnRecord.CustomerSn = customeSN;
            await tranSnRecordRepo.UpdateAsync(transSnRecord, s => new
            {
                s.CustomerSn,
            });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "[存档后处理事件异常] {SN}, 工位：{OpCode}",
                notification.SN,
                notification.OpCode);
        }
    }
}
